package com.example.mytools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author written by Shen Xiaoliang(Mark Shen)
 *
 */
public class MainActivity extends Activity {
	private static final boolean isTiny4412 = false;
	private static final int NOTIFICATION_ID = 100, APP_STOP = 1;
	private String startADB = null, stopADB = null, noWIFI = null;
	private TextView hint1 = null, hint2 = null;
	private Button btnIP = null, btnStart = null, btnStop = null, btnLeave = null;
	private NotificationManager mNotificationManager = null;
	private NotificationCompat.Builder mBuilder = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		startADB = this.getString(R.string.textview_start);
		stopADB = this.getString(R.string.textview_stop_leave);
		noWIFI = this.getString(R.string.no_wifi);
		
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	    mBuilder = new NotificationCompat.Builder(this);
	    mBuilder.setContentTitle(this.getString(R.string.notification_title))
        	.setContentText(this.getString(R.string.notification_text))
        	.setContentIntent(getDefalutIntent(Notification.FLAG_NO_CLEAR))
        	.setTicker(this.getString(R.string.notification_title))
        	.setWhen(System.currentTimeMillis())
        	.setOngoing(false)
        	.setSmallIcon(R.drawable.ic_launcher);
		
		hint1 = (TextView) findViewById(R.id.hint1);
		hint2 = (TextView) findViewById(R.id.hint2);
		
		iniButton();
	    checkVersion();
	    getprop();
	    isRoot();
	}

	/**
	 * See if tcp-adb has started already
	 */
	private void getprop() {
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("getprop service.adb.tcp.port");
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			String str = bf.readLine();
			if(str != null){
				if(str.equals("5555")){
					btnStart.setEnabled(false);
					mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
				}else{
					btnStop.setEnabled(false);
				}
			}
		
			process.destroy();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void checkVersion() {
		int version = getApplicationInfo().targetSdkVersion;
		if(version <= Build.VERSION_CODES.GINGERBREAD){
			new AlertDialog.Builder(this)
            .setMessage(this.getString(R.string.vision_text))
            .setPositiveButton(this.getString(R.string.exit_button),
            		new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							System.exit(0);
						}
					})
            .show();
		}
	}

	private void isRoot() {
		try{
	    	if((!new File("/system/bin/su").exists())
	    			&& (!new File("/system/xbin/su").exists())) {
	    		btnStop.setEnabled(false);
				btnStart.setEnabled(false);
				new AlertDialog.Builder(this)
				               .setMessage(this.getString(R.string.root_text))
				               .setPositiveButton(this.getString(R.string.positive_button), null)
				               .show();
	    	}
	    }catch (Exception e) {
	    	// TODO Auto-generated catch block
	    	e.printStackTrace();
	    }
	}

	private void iniButton() {
		btnIP = (Button) findViewById(R.id.btn_ip);
		btnIP.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (getIP()) {
					hint1.setText(" ");
				}else{
					hint1.setText(noWIFI);
				}
			}
		});

		btnStart = (Button) findViewById(R.id.btn_start);
		btnStart.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setTcpAdb(5555);
				getIP();
				hint1.setText(startADB);
				btnStop.setEnabled(true);
				btnStart.setEnabled(false);
				mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
			}
		});

		btnStop = (Button) findViewById(R.id.btn_stop);
		btnStop.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setTcpAdb(-1);
				hint1.setText(stopADB);
				hint2.setText(" ");
				btnStart.setEnabled(true);
				btnStop.setEnabled(false);
				mNotificationManager.cancelAll();
				
				thrLeaving thr = new thrLeaving(1200);
				thr.start();
			}
		});

		btnLeave = (Button) findViewById(R.id.btn_leave);
		btnLeave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				thrLeaving thr = new thrLeaving(300);
				thr.start();
			}
		});
	}
	
	/**
	 * Run before you drop out
	 */
	private class thrLeaving extends Thread{
		private long ms = 0;
		
		public thrLeaving(long msecond){
			ms = msecond;
		}
		
	    public void run() {
	    	try {
				Thread.sleep(ms);
		    	Message message = new Message();
		    	message.what = APP_STOP;
		    	handler.sendMessage(message);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	     }
	}
	
	private PendingIntent getDefalutIntent(int flags){
		Intent intent = new Intent(this, MainActivity.class);
	    PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, flags);
	    return pendingIntent;
	}
	
	private boolean getIP() {
		WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		if (wm.isWifiEnabled() || wm.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
			execIfconfig("wlan0");
			return true;
		}else{
			if (isTiny4412) {
				execIfconfig("eth0");
				return true;
			}
			return false;
		}
	}

	private void execIfconfig(String device) {
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("ifconfig " + device);
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			String str = bf.readLine();
			if (str.length() > 30) {
				int i = 0;
				for (i = 17; i < 30; i++) {
					if (str.charAt(i) == ' ') {
						break;
					}
				}
				hint2.setText("ip: " + str.subSequence(10, i));
			}

			process.destroy();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setTcpAdb(int port) {
		Process process = null;
		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes("stop adbd\n");
			os.writeBytes("setprop service.adb.tcp.port " + port + "\n");
			os.writeBytes("start adbd\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@SuppressLint("HandlerLeak") 
	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case APP_STOP:
				System.exit(0);
				break;
			}
		}
	};
}
